from decimal import Decimal
from django.db.models import Sum, Count, Avg
from datetime import datetime, timedelta
from .models import TransactionRecord, DriverAccount
from order.models import Order
from login.models import User
import logging

logger = logging.getLogger(__name__)

class DriverIncomeAnalyzer:
    """司机收入分析器"""
    
    def analyze_driver_income(self, driver_id, start_date, end_date):
        """
        分析司机收入
        :param driver_id: 司机ID
        :param start_date: 开始日期 (YYYY-MM-DD)
        :param end_date: 结束日期 (YYYY-MM-DD)
        :return: 分析结果字典
        """
        try:
            # 确保driver_id是整数
            try:
                driver_id = int(driver_id)
            except (ValueError, TypeError):
                return {"error": "司机ID格式错误"}
            
            # 验证司机是否存在
            try:
                driver = User.objects.get(id=driver_id)
            except User.DoesNotExist:
                return {"error": "司机不存在"}
            
            # 转换日期格式
            start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
            end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1) - timedelta(seconds=1)
            
            # 获取交易记录
            transactions = TransactionRecord.objects.filter(
                driver_id=driver,
                transaction_type=0,  # 收入
                transaction_time__range=(start_datetime, end_datetime)
            )
            
            # 获取订单数据
            orders = Order.objects.filter(
                driver_id=driver_id,
                order_status=4,  # 已支付
                create_time__range=(start_datetime, end_datetime)
            )
            
            # 基础统计
            total_income = transactions.aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
            total_orders = orders.count()
            avg_order_amount = orders.aggregate(avg=Avg('order_amount'))['avg'] or Decimal('0.00')
            
            # 按日期分组统计
            daily_stats = transactions.extra(
                select={'date': 'DATE(transaction_time)'}
            ).values('date').annotate(
                daily_income=Sum('amount'),
                order_count=Count('id')
            ).order_by('date')
            
            # 转换日期格式为字符串
            daily_breakdown = []
            for stat in daily_stats:
                daily_breakdown.append({
                    "date": stat['date'].strftime('%Y-%m-%d') if hasattr(stat['date'], 'strftime') else str(stat['date']),
                    "income": float(stat['daily_income']),
                    "orders": stat['order_count']
                })
            
            # 计算趋势
            if len(daily_stats) > 1:
                first_day_income = daily_stats[0]['daily_income']
                last_day_income = daily_stats[-1]['daily_income']
                if first_day_income > 0:
                    growth_rate = ((last_day_income - first_day_income) / first_day_income) * 100
                else:
                    growth_rate = 0
            else:
                growth_rate = 0
            
            # 生成分析报告
            analysis_result = {
                "driver_info": {
                    "driver_id": driver_id,
                    "driver_name": driver.real_name,
                    "phone": driver.phone
                },
                "period": {
                    "start_date": start_date,
                    "end_date": end_date,
                    "days": (end_datetime - start_datetime).days + 1
                },
                "summary": {
                    "total_income": float(total_income),
                    "total_orders": total_orders,
                    "avg_order_amount": float(avg_order_amount),
                    "growth_rate": round(growth_rate, 2)
                },
                # 前端期望的字段名
                "total_income": float(total_income),
                "order_count": total_orders,
                "avg_order_amount": float(avg_order_amount),
                "active_days": len(daily_breakdown),
                "trend_data": daily_breakdown,
                "daily_breakdown": daily_breakdown,
                "analysis": {
                    "analysis_summary": self._generate_analysis_summary(
                        total_income, total_orders, avg_order_amount, growth_rate
                    ),
                    "recommendations": self._generate_recommendations(
                        total_income, total_orders, avg_order_amount, growth_rate
                    )
                }
            }
            
            logger.info(f"司机 {driver_id} 收入分析完成")
            return analysis_result
            
        except Exception as e:
            logger.error(f"收入分析失败: {str(e)}")
            return {"error": f"收入分析失败: {str(e)}"}
    
    def _generate_analysis_summary(self, total_income, total_orders, avg_order_amount, growth_rate):
        """生成分析摘要"""
        summary = f"在分析期间，司机总收入为¥{total_income}，共完成{total_orders}笔订单，"
        summary += f"平均订单金额为¥{avg_order_amount}。"
        
        if growth_rate > 0:
            summary += f"收入增长率为{growth_rate}%，表现良好。"
        elif growth_rate < 0:
            summary += f"收入增长率为{growth_rate}%，需要关注。"
        else:
            summary += "收入保持稳定。"
        
        return summary
    
    def _generate_recommendations(self, total_income, total_orders, avg_order_amount, growth_rate):
        """生成优化建议"""
        recommendations = []
        
        if total_orders < 10:
            recommendations.append("建议增加接单频率，提高订单数量")
        
        if avg_order_amount < 20:
            recommendations.append("建议选择距离较远的订单，提高单笔收入")
        
        if growth_rate < 0:
            recommendations.append("收入呈下降趋势，建议优化服务时间和服务质量")
        
        if not recommendations:
            recommendations.append("收入表现良好，继续保持当前服务水平")
        
        return recommendations 